package com.ml4ai.backend.web;

import com.ml4ai.backend.dto.EnumQueryDTO;
import com.ml4ai.backend.utils.RestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by uesr on 2018/9/4.
 */
@Api("公共查询")
@RestController
@RequestMapping("/api/public")
public class WebRest {

    @ApiOperation("枚举查询")
    @RequestMapping(value = "/enums", method = RequestMethod.POST)
    public Map<String, Object> queryEnum(@RequestBody EnumQueryDTO enumQuery) {
        Map<String, Object> kv = new LinkedHashMap<>();
        try {
            Class<?> enumClass = Class.forName("com.ml4ai.backend.domain.base." + enumQuery.getEnumname());
            if (!enumClass.isEnum()) {
                return RestUtil.failure("传入的类型根无效");
            } else {
                Method valuesMethod = enumClass.getMethod("values");
                Object[] values = (Object[]) valuesMethod.invoke(null);
                for (Object value : values) {
                    String key = value.toString();
                    if (enumQuery.getExcludeType() == null || !enumQuery.getExcludeType().contains(key)) {
                        Method getNameMethod = enumClass.getMethod("getName");
                        String name = (String) getNameMethod.invoke(value);
                        kv.put(key, name);
                    }
                }
            }
        } catch (Exception e) {
            return RestUtil.failure("传入的类型根无效");
        }
        return RestUtil.success(kv);
    }


}
